from fastapi import FastAPI, File, UploadFile, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import shutil
import os

app = FastAPI()

# 启用 CORS 中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 可以指定具体的前端URL地址
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有HTTP方法 (GET, POST, OPTIONS等)
    allow_headers=["*"],  # 允许所有请求头
)

# 初始化模板
templates = Jinja2Templates(directory="templates")

# 文件上传接口
@app.post("/uploading")
async def upload_file(file: UploadFile = File(...)):
    # 确保保存目录存在
    upload_folder = "uploaded_files"
    os.makedirs(upload_folder, exist_ok=True)

    try:
        # 保存文件到指定位置
        file_location = os.path.join(upload_folder, file.filename)
        with open(file_location, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # 返回成功信息
        return {"info": f"文件: '{file.filename}'   保存路径: '{file_location}'"}

    except Exception as e:
        # 返回错误信息
        raise HTTPException(status_code=500, detail=f"文件上传失败: {str(e)}")

# 显示首页
@app.get("/", response_class=HTMLResponse)
async def read_index(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})
